home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4467 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.1 KB  |  77 lines

  1. Path: ix.netcom.com!netnews
  2. From: miker3@ix.netcom.com (Mike Rubenstein)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: should operator== and operator= be virtual?
  5. Date: Tue, 30 Jan 1996 12:30:02 GMT
  6. Organization: Netcom
  7. Message-ID: <310e0cf6.52459584@nntp.ix.netcom.com>
  8. References: <4ejvkr$btb@itnews.sc.intel.com>
  9. NNTP-Posting-Host: ix-dc8-20.ix.netcom.com
  10. X-NETCOM-Date: Tue Jan 30  4:30:17 AM PST 1996
  11. X-Newsreader: Forte Agent .99c/16.141
  12.  
  13. etse@scdt.intel.com (Eric Tse) wrote:
  14.  
  15. > Hi,
  16. > Should operator==() and operator=() of a class be virtual if the class is
  17. > planned for extensibility? Personally I think in general assignement 
  18. > operators should be non-virtual, but I am not sure about equality operator.
  19. > Could anyone helps? Thanks.
  20. > class A {
  21. > public:
  22. >   A& operator=(const A&);
  23. >   virtual bool operator==(const A&) const;
  24. >   virtual bool operator!=(const A&) const;
  25. > };  
  26. > class B : public A {
  27. > public:
  28. >   B& operator=(const B&);
  29. >   
  30. >   virtual bool operator==(const A&) const; // ?
  31. >   virtual bool operator!=(const A&) const; // ?
  32. >   virtual bool operator==(const B&) const; // ?
  33. >   virtual bool operator!=(const B&) const; // ?
  34. > };
  35.  
  36. Why do you think assignment operators should be non-virtual?  Any
  37. function that a derived class may want to override should usually be
  38. made virtual.
  39.  
  40. operator= is a special case.  Even if there is no explicit override of
  41. operator=, it is not inheritted.  If a class does not provide
  42. operator=, a default one will be generated that does a memberwise
  43. copy.  So, even if the derived classes never explicitly override
  44. operator=, you probably need to make it virtual if any derived classes
  45. may add data members.
  46.  
  47. Example:
  48.  
  49.     class A {
  50.       public: 
  51.         A& operator=(const A&);
  52.     };
  53.  
  54.     class B : public A {
  55.       private:
  56.         int i;
  57.     };
  58.  
  59.     A* a = new B;
  60.     B b;
  61.     (*a) = b;
  62.  
  63. This will not work right; A::operator= will be called and B::i will
  64. not be copied.
  65.  
  66. operator== should be virtual if a derived class may want to override
  67. it.  I'd guess that usually this means it should be virtual (read: in
  68. my programs I almost always want it virtual), but there probably are
  69. examples where it makes no sense to override it.
  70.  
  71.  
  72. Michael M Rubenstein
  73.